package com.scalar.chiptrack.adaptor.tsmc;

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.html.parser.DTD;
import javax.swing.text.html.parser.DocumentParser;
import javax.swing.text.MutableAttributeSet;
import java.io.Reader;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

/**
 * Created by ChandraSekhar.
 * Date: June 06, 2007
 * Time: 3:24:11 PM
 */
public class TSMCHtmlParser extends HTMLEditorKit.ParserCallback
{
    private ArrayList<TSMCLotStatus> m_pcmDataList = new ArrayList<TSMCLotStatus>();
    private String m_token;
	private boolean m_isInput;
    private boolean needTableDataParsing;
    private int m_rowIndex;
    private int m_cellIndex;
    private boolean m_cellOpen;
    private boolean m_readyForParsing;
    private int m_tableTagCount;
    private boolean m_rowStart;
    private boolean m_tableStart;
    private TSMCLotStatus m_pcmData;
    private String m_bvSessionId;

	public TSMCHtmlParser()
    {
        needTableDataParsing = true;
	}

    public TSMCHtmlParser(String bvSessionId )
    {
        m_cellOpen = false;
        m_cellIndex = -1;
        m_rowIndex = -1;
        m_tableStart = false;
        m_rowStart = false;
        m_readyForParsing = false;
        m_tableTagCount = 0;
        m_pcmDataList = new ArrayList();
        m_bvSessionId = bvSessionId;

    }
	public void parse(Reader reader) throws Exception{
                
		DTD dtd = DTD.getDTD("HTML");
		DocumentParser documentParser = new DocumentParser (dtd);
        documentParser.parse (reader, this, true /*ignore CharSet*/);
   	}

    public ArrayList parsePCM(Reader reader) throws Exception{

		DTD dtd = DTD.getDTD("HTML");
		DocumentParser documentParser = new DocumentParser (dtd);
        documentParser.parse (reader, this, true /*ignore CharSet*/);

        return m_pcmDataList;
	}
	public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos)
    {

        String fileLink = null;
        String finalFileUrl = null;
        String fileName = null;
        String hashValue = null;
        
        if( needTableDataParsing )
        {
            if(t == HTML.Tag.INPUT){

                //System.out.println();

                HTML.Attribute name = HTML.getAttributeKey("name");
                HTML.Attribute value = HTML.getAttributeKey("value");
                if( "org.apache.struts.taglib.html.TOKEN".equalsIgnoreCase((String)a.getAttribute(name))){
                    setToken((String)a.getAttribute(value));
                }

                m_isInput = true;

            }else{
                m_isInput = false;
            }
        }
        else
        {

            // Got a Table Tag
            if (t == HTML.Tag.TABLE)
            {
                if (m_tableStart == false)
                {
                    m_tableTagCount++;
                    m_rowIndex = -1;
                    m_tableStart = true;
                    m_rowStart = false;
                    m_cellOpen = false;
                }
                else
                {
                    m_tableStart = false;
                }
                //System.out.println("m_tableTagCount = " + m_tableTagCount);
                if (m_tableTagCount == 10) {             // Start of Results Table
                    //m_readyForParsing = true;
                }
                else if (m_tableTagCount == 25) {      // Reached End of Results Table
                    m_readyForParsing = false;
                }
            }

            if ((t == HTML.Tag.A) && (a.isDefined ("onmousedown") == true))
            {
                fileLink = (String) a.getAttribute("onmousedown"); // Looks something like ===>  this.href=linkTo('/e/wsm/tsmc/u460/q6058701.wsm','2305')


                //http://dst.tsmc.com/cgi-bin/download_check?pmFileType=2&pmUserID=205485&pmCatOID=-9912&pmFile=/e/wpr/tsmc/u696/n1g84700.wpr&pmHash=2361&pmProjMgrFlag=0&BV_SessionID=undefined&pmDocReqID=0
                try
                {
                    if ( fileLink != null && fileLink.indexOf(".wpr") != -1 )
                    {
                        //System.out.println ("fileLink = " + fileLink);

                        StringTokenizer st = new StringTokenizer(fileLink, "\'");
                        st.nextToken(); // this.href=linkTo(
                        fileName = st.nextToken();
                        //System.out.println("fileName = " + fileName);
                        st.nextToken(); // ,
                        hashValue = st.nextToken();

                        finalFileUrl = "/cgi-bin/download_check?pmFileType=2&pmUserID=205485&pmCatOID=-9912" +
                                       "&pmFile=" + fileName + "&pmHash=" + hashValue + "&pmProjMgrFlag=0" +"BV_SessionID=" + m_bvSessionId +"&pmDocReqID=0";


                        //System.out.println ("finalFileUrl = " + finalFileUrl);
                    }
                }
                catch (NoSuchElementException ignore) {
                    // no links in this row
                }


                if (finalFileUrl != null)
                {
                    if (fileName.endsWith ("wpr"))
                    {
                        m_pcmData.setBinFileHyperLink ( finalFileUrl );
                        //System.out.println("fileName = " + fileName);
                       // m_pcmData.setBinFileName( fileName );
                    }
                }

            }

            // Got a new row tag
            if (t == HTML.Tag.TR)
            {

                if (m_rowStart == false) {

                    m_rowIndex ++;
                    m_cellIndex = -1;
                    m_rowStart = true;
                    m_cellOpen = false;
                }
                else {
                    m_rowStart = false;
                }

                if (m_tableTagCount == 10)
                {

                    if (m_rowIndex <= 1 ) {  // Table Header Rows .. skip them
                        m_readyForParsing = false;
                    }
                    else {
                        m_readyForParsing = true;
                    }
                }
            }

            // Got a new cell
            if (t == HTML.Tag.TD) {
                if (m_cellOpen == false) {
                    m_cellIndex ++;
                    m_cellOpen = true;
                }
                else {
                    m_cellOpen = false;
                }
            }
        }

	}

	public void handleText (char[] data, int pos)
    {
		if (m_readyForParsing == false) {
            return;
        }

        String text = new String ( data );
        if (text == null) text = "";
        text = text.trim();

        int index = text.indexOf('&');
        if (index != -1) {
            text = text.substring (0, index);
        }

       // System.out.println("text = " + text);

        switch (m_cellIndex) 
        {               
            case 0:
                //System.out.println ("0->" + text);
                m_pcmData = new TSMCLotStatus();
                //m_pcmData.setCustProduct (text);
                break;

            case 1:
                //System.out.println ("1->" + text);
                //m_pcmData.setTsmcProduct (text);
                break;

            case 2:
                //System.out.println ("2->" + text);
                //m_pcmData.setCustLotId (text);
                break;

            case 3:
                //System.out.println ("3-> LotNumber: " + text);
                if ( text != null && !text.startsWith("TSMC Lot") )
                {
                    m_pcmData.setCustomerLotID ( text ) ;
                }
                break;

            case 4:
                //System.out.println ("4->" + text);
                break;

            case 5:
                //System.out.println ("5->" + text);
                break;

            case 6:
                //System.out.println ("6->" + text);
                break;
            case 7:
                    //System.out.println ("7->" + text);
                    /*if ( text != null && "BIN".equalsIgnoreCase(text ) )
                    {
                        m_pcmDataList.add (m_pcmData);
                    }*/
                break;

            case 8:
                //System.out.println ("8->" + text);
                
                break;
            case 9:
                //System.out.println ("9->" + text);
				if ( text != null && "WPR".equalsIgnoreCase(text ) )
                {
                    m_pcmDataList.add (m_pcmData);
                }
                break;

            default:
                //System.out.println ("cell index : " + m_cellIndex + " -> " + text);
                break;
        }
    }

	public void setToken(String token){
		m_token = token;
	}

	public String getToken(){
		return m_token;
	}
}
